package com.hy.mechanicalarm.ui.activity;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.hy.mechanicalarm.R;
import com.hy.mechanicalarm.baseapp.BaseActivity;
import com.hy.mechanicalarm.constant.Constants;
import com.hy.mechanicalarm.ui.fragment.WarmingDialogFragment;
import com.hy.mechanicalarm.ui.service.SocketService;
import com.hy.mechanicalarm.ui.view.CustomWaveView;
import com.hy.mechanicalarm.ui.view.VerticalProgressBar;
import com.hy.mechanicalarm.utils.CommonUtil;
import com.hy.mechanicalarm.utils.SPUtil;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 *  2018/8/5 15:10
 *  hanyin
 *  hanyinit@163.com
 */
public class MainActivity extends BaseActivity implements View.OnClickListener,WarmingDialogFragment.WarmingDialogListener {
    @BindView(R.id.imageSetting)
    ImageView imageSetting;
    @BindView(R.id.viewHHW)
    CustomWaveView waveView;
    @BindView(R.id.iv_progressBar)
    VerticalProgressBar ivProgressBar;
    private int currentProgress = 0;
    private int maxProgress = 1000;
    @BindView(R.id.tvThemometer)
    TextView tvThemometer;
    @BindView(R.id.imageMeasureSwitch)
    ImageView imageMeasureSwitch;
    @BindView(R.id.imageExplain)
    ImageView imageExplain;
    int hhwDatas = 0;
    boolean measureSwitch = false;
    private MessageBackReciver mReciver;
    private IntentFilter mIntentFilter;
    private LocalBroadcastManager mLocalBroadcastManager;
    private String  startMeasureOrder= "AA55000905000eCC33";
    private String  measureDataOrder = "AA550009070010CC33";//AA55001107 0100 0035 0000 0000 000dCC33
    private String  stopMeasureOrder = "AA55000904000dCC33";
    private String  positionOrder    = "AA55000906000fCC33";
    SPUtil spUtil = null;
    WarmingDialogFragment dialog = null;
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what){
                case 0:
                    waveView.start();
                    waveView.setCurrentProgress(currentProgress);
                    if((hhwDatas-currentProgress)/10>1){
                        currentProgress +=10;
                    }else{
                        currentProgress =hhwDatas;
                    }
                    break;
                case 1:
                    measureDataOrder();
                    int haltTime = spUtil.getInt(Constants.HALT_TIMES,60*1000);
                    int measureTime =  spUtil.getInt(Constants.MEASURE_TIMES,30*1000);
                    handler.sendEmptyMessageDelayed(1,Long.valueOf((haltTime+measureTime))*1000);
                    break;
                case 2:
                    socketService.sendMsg(positionOrder);
                    handler.sendEmptyMessageDelayed(2,60*60*1000);
                    break;
                default:
                    break;
            }
        }
    };
    @Override
    public void initView() {
        super.initView();
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);


    }

    @Override
    public void initData() {
        super.initData();
        initProgressBar();
        //设置圆的半径
        waveView.setRadius(80);
        //设置进度最大值
        waveView.setMaxProgress(maxProgress);
        //设置进度的当前值
        waveView.setCurrentProgress(currentProgress);

        spUtil = new SPUtil(this);
        imageMeasureSwitch.setVisibility(View.GONE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
        mReciver = new MessageBackReciver();
        mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(SocketService.HEART_BEAT_ACTION);
        mIntentFilter.addAction(SocketService.MESSAGE_ACTION);
        mLocalBroadcastManager.registerReceiver(mReciver, mIntentFilter);
        imageMeasureSwitch.setVisibility(View.GONE);
        String MEASURE_X = spUtil.getString(Constants.MEASURE_X,"0");
        String MEASURE_Y = spUtil.getString(Constants.MEASURE_Y,"0");
        String MEASURE_Z = spUtil.getString(Constants.MEASURE_Z,"0");
        String GATE_POSITION_X = spUtil.getString(Constants.GATE_POSITION_X,"0");
        String GATE_POSITION_Y = spUtil.getString(Constants.GATE_POSITION_Y,"0");
        String GATE_POSITION_Z = spUtil.getString(Constants.GATE_POSITION_Z,"0");

        if(!"0".equals(MEASURE_X)||!"0".equals(MEASURE_Y)||!"0".equals(MEASURE_Z)
                ||!"0".equals(GATE_POSITION_X)||!"0".equals(GATE_POSITION_Y)||!"0".equals(GATE_POSITION_Z)){
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {

                    startMeasureOrder();
                    int haltTime = spUtil.getInt(Constants.HALT_TIMES,60*1000);
                    int measureTime =  spUtil.getInt(Constants.MEASURE_TIMES,30*1000);
                    handler.sendEmptyMessageDelayed(1,Long.valueOf((haltTime+measureTime)*1000));
                    handler.sendEmptyMessageDelayed(2,60*60*1000);

                }
            },5000);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        handler.removeMessages(1);
    }

    private void measureDataOrder() {
        socketService.sendMsg(measureDataOrder);
    }

    private void startMeasureOrder() {
        socketService.sendMsg(startMeasureOrder);
        measureSwitch = true;

    }

    @Override
    public void initListener() {
        super.initListener();
        imageSetting.setOnClickListener(this);
        imageMeasureSwitch.setOnClickListener(this);
        imageExplain.setOnClickListener(this);
    }



    @Override
    protected void onStop() {
        super.onStop();
        handler.removeMessages(1);
        handler.removeMessages(2);
        socketService.sendMsg(stopMeasureOrder);
        mLocalBroadcastManager.unregisterReceiver(mReciver);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onWarmingDialog() {
        WarmingDialogFragment.isStatus  = false;
        CommonUtil.showToast("预警系统开启");
    }

    class MessageBackReciver extends BroadcastReceiver {

        public MessageBackReciver() {
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(SocketService.HEART_BEAT_ACTION)) {

            } else {
                String message = intent.getStringExtra("message");

                if("05".equals(message.substring(8,10))){
                    //开始测量
                    String data = message.substring(14,18);
                    if("0000".equals(data)){
                        CommonUtil.showToast("开始测量");
                        imageMeasureSwitch.setVisibility(View.VISIBLE);
                        imageMeasureSwitch.setImageResource(R.drawable.btn_zt);
                    }
                }else if("04".equals(message.substring(8,10))){
                    //停止测量
                    String data = message.substring(14,18);
                    if("0000".equals(data)){

                        CommonUtil.showToast("停止测量");
                    }
                }else if("06".equals(message.substring(8,10))){
                    //位置校准
                    String data = message.substring(14,18);
                    if("0000".equals(data)){

                        CommonUtil.showToast("位置校准");
                    }
                }else if("07".equals(message.substring(8,10))){
                    //获取测量数据
                    //AA55 0011 07 0100 0035 0000 0000 000d CC33
                    String hhwData = message.substring(10,14);
                    String wdData = message.substring(14,18);
                    hhwDatas= Integer.parseInt(hhwData,16);
                    double b = Integer.parseInt(wdData,16)/10.0;
                    ivProgressBar.setMax(3000);
                    ivProgressBar.setProgress(Integer.parseInt(wdData,16));
                    tvThemometer.setText(b+"℃");
                    showWarming(Integer.parseInt(hhwData,16),Integer.parseInt(wdData,16));

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            while (currentProgress < Integer.parseInt(hhwData,16)){
                                try {
                                    Thread.sleep(100);
                                    handler.sendEmptyMessage(0);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }

                            }
                        }
                    }).start();
                }
            }
        }
    }

    /**
     * 显示警告
     * @param hhwDatas
     * @param wdDatas
     */
    private void showWarming(int hhwDatas, int wdDatas) {
        int compound_calibration = spUtil.getInt(Constants.COMPOUND_CALIBRATION,5)*10;
        int compound_min = spUtil.getInt(Constants.COMPOUND_MIN,0)*10-compound_calibration;
        int compound_max = spUtil.getInt(Constants.COMPOUND_MAX,25)*10+compound_calibration;
        int temperature_calibration = spUtil.getInt(Constants.TEMPERATURE_CALIBRATION,5)*10;
        int temperature_min = spUtil.getInt(Constants.TEMPERATURE_MIN,0)*10-temperature_calibration;
        int temperature_max = spUtil.getInt(Constants.TEMPERATURE_MAX,200)*10+temperature_calibration;
        int flag = 0;
        if((hhwDatas<compound_min||hhwDatas>compound_max)){
            flag += 1;
        }
        if(wdDatas<temperature_min||wdDatas>temperature_max){
            flag += 2;
        }
        if(flag != 0 ){
            showWarmingDialog(flag);
        }
        /*if((hhwDatas<compound_min||hhwDatas>compound_max)&&(wdDatas<temperature_min||wdDatas>temperature_max)){
            showWarmingDialog(2);
        }else if((hhwDatas<compound_min||hhwDatas>compound_max)&&(wdDatas>=temperature_min&&wdDatas<=temperature_max)){
            showWarmingDialog(0);
        }else if((hhwDatas>=compound_min&&hhwDatas<=compound_max)&&(wdDatas<temperature_min||wdDatas>temperature_max)){
            showWarmingDialog(1);
        }*/
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.imageSetting:
                socketService.sendMsg(positionOrder);
                startActivity(new Intent(MainActivity.this,SettingActivity.class));
                break;
            case R.id.imageMeasureSwitch:
                if(measureSwitch){
                    imageMeasureSwitch.setImageResource(R.drawable.btn_ks);
                    socketService.sendMsg(stopMeasureOrder);
                    handler.removeMessages(1);
                    handler.removeMessages(2);
                    measureSwitch = false;
                }else{
                    startMeasureOrder();
                    int haltTime = spUtil.getInt(Constants.HALT_TIMES,60*1000);
                    int measureTime =  spUtil.getInt(Constants.MEASURE_TIMES,30*1000);
                    handler.sendEmptyMessageDelayed(1,Long.valueOf((haltTime+measureTime)*1000));
                    handler.sendEmptyMessageDelayed(2,60*60*1000);
                }
                break;
            case R.id.imageExplain:
                //startActivity(new Intent(MainActivity.this,HelpActivity.class));
                break;

        }
    }
    public void showWarmingDialog(int flag)
    {
        int lastFlag = spUtil.getInt("isDialog",0);

         if(!WarmingDialogFragment.isStatus()||flag != lastFlag){
             if(dialog!=null){
                 dialog.dismiss();
             }
             spUtil.putInt("isDialog",flag);
             dialog = new WarmingDialogFragment(flag);
             dialog.show(getFragmentManager(),"WarmDialog");
        }
    }
    private void initProgressBar() {
        ivProgressBar.setMax(3000);
        ivProgressBar.setProgress(260);
        double a = 260/10.0;
        tvThemometer.setText(a+"℃");
    }
}
